package com.yourpackage;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.common.WXModule;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

public class BluetoothClassicModule extends WXModule {

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothSocket bluetoothSocket;
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 常用UUID

    @JSMethod(uiThread = true)
    public void connectToDevice(String address, JSONObject callback) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            bluetoothSocket.connect();
            callback.put("status", "success");
        } catch (IOException e) {
            e.printStackTrace();
            callback.put("status", "fail");
        }
    }

    @JSMethod(uiThread = true)
    public void sendFile(String filePath, JSONObject callback) {
        if (bluetoothSocket == null || !bluetoothSocket.isConnected()) {
            callback.put("status", "not connected");
            return;
        }
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = bluetoothSocket.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            fis.close();
            os.close();
            callback.put("status", "success");
        } catch (IOException e) {
            e.printStackTrace();
            callback.put("status", "fail");
        }
    }

    @JSMethod(uiThread = true)
    public void disconnect(JSONObject callback) {
        try {
            if (bluetoothSocket != null) {
                bluetoothSocket.close();
                callback.put("status", "success");
            }
        } catch (IOException e) {
            e.printStackTrace();
            callback.put("status", "fail");
        }
    }
}
